/**
 * 
 */
package com.example.radioclub.music.tasks;

import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.example.radioclub.data.Constants;
import com.example.radioclub.music.interfaces.IRestMusic;

import android.os.AsyncTask;
import android.util.Log;

/**
 * This task brings certificate for playing certain MelOn contents.
 * 
 * @author wizard
 * 
 */
public class RestCertificateDownloader extends AsyncTask<Void, Void, String> {
	private final String TAG = Constants.APP_TAG + getClass().getName();
	private RestTemplate mapiRestTemplate = null;
	private IRestMusic listener;
	private MultiValueMap<String, String> map = null;

	/**
	 * Default constructor for RestCertificateDownloader class.
	 * 
	 * @param mapiRestTemplate the REST Template you would use for this class. Please 
	 * 			use REST Template that has cookie.
	 * @param userId user Id whose belongs to user who want to access full streaming.
	 * @param songId the Id of the song user with userId wants to stream
	 * @param channelCd channel Code provided by authentication itself.
	 * @param contentType this goes be default 'M' means music. Just change if you need.
	 * @param listener an interface you might want to use.
	 */
	public RestCertificateDownloader(RestTemplate mapiRestTemplate, String userId, String songId, String channelCd, String contentType, IRestMusic listener) {
		this.mapiRestTemplate = mapiRestTemplate;
		this.map = new LinkedMultiValueMap<String, String>();
		this.map.add("userId", userId);
		this.map.add("songId", songId);
		this.map.add("channelCd", channelCd);
		this.map.add("contentType", contentType);
		this.listener = listener;
		// Log.i(TAG, userId + "," + map.get("songId") + "," + map.get("channelCd") + "," + map.get("contentType"));
	}
	
	@Override
	protected String doInBackground(Void... params) {
		// TODO Auto-generated method stub
		try {
			ResponseEntity<String> response = this.mapiRestTemplate.postForEntity(Constants.API_MELON_CERTIFICATE, this.map, String.class);
			return response.getBody();			
		} catch (Exception e) {
			e.printStackTrace();
			Log.i(TAG, e.getMessage());
		}
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		Log.i(TAG, (result != null ? result : "Nothing is here, Sorry."));
		this.listener.onCertificateDownloadFinished(result);
	}

}
